package com.muyan.sys.webscoket.util;

import com.muyan.sys.webscoket.service.ServerInstanceManager;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class ChannelManager {
    private static final ConcurrentHashMap<String, Channel> userChannelMap = new ConcurrentHashMap<>();
    private final RabbitTemplate rabbitTemplate;
    private final ServerInstanceManager serverInstanceManager;
    private final RedisTemplate<String, String> redisTemplate;
    
    public ChannelManager(RabbitTemplate rabbitTemplate, 
                         ServerInstanceManager serverInstanceManager,
                         RedisTemplate<String, String> redisTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        this.serverInstanceManager = serverInstanceManager;
        this.redisTemplate = redisTemplate;
    }
    
    /**
     * 添加用户通道
     */
    public void addChannel(String userId, Channel channel) {
        userChannelMap.put(userId, channel);
        
        // 将用户-服务器映射存储到Redis
        String serverId = serverInstanceManager.getServerId();
        redisTemplate.opsForHash().put("user_server_map", userId, serverId);
        
        // 将用户添加到服务器用户集合
        String serverUsersKey = "server_users:" + serverId;
        redisTemplate.opsForSet().add(serverUsersKey, userId);
    }
    
    /**
     * 移除用户通道
     */
    public void removeChannel(String userId) {
        userChannelMap.remove(userId);
        
        // 从Redis中移除用户-服务器映射
        String serverId = serverInstanceManager.getServerId();
        redisTemplate.opsForHash().delete("user_server_map", userId);
        
        // 从服务器用户集合中移除用户
        String serverUsersKey = "server_users:" + serverId;
        redisTemplate.opsForSet().remove(serverUsersKey, userId);
    }
    
    /**
     * 获取用户通道
     */
    public Channel getChannel(String userId) {
        log.info("userChannelMap=={}",userChannelMap);
        return userChannelMap.get(userId);
    }
    
    /**
     * 获取用户通道映射
     */
    public ConcurrentHashMap<String, Channel> getUserChannelMap() {
        return userChannelMap;
    }
    
    /**
     * 检查用户是否在线
     */
    public boolean isOnline(String userId) {
        // 首先检查本地通道
        log.info("userId=={}",userChannelMap);
        Channel localChannel = userChannelMap.get(userId);
        log.info("localChannel=={}",localChannel);
        if (localChannel != null && localChannel.isActive()) {
            return true;
        }
        
        // 检查Redis中的用户-服务器映射
        String serverId = (String) redisTemplate.opsForHash().get("user_server_map", userId);
        return serverId != null;
    }
    
    /**
     * 关闭用户通道
     */
    public void closeChannel(String userId) {
        Channel channel = userChannelMap.get(userId);
        if (channel != null) {
            channel.close();
            removeChannel(userId);
        }
    }
    
    /**
     * 获取用户所在的服务器ID
     */
    public String getUserServerId(String userId) {
        return (String) redisTemplate.opsForHash().get("user_server_map", userId);
    }
} 